/**
 * 是否合法IP地址
 * @param rule
 * @param value
 * @param callback
 */
export function validateIP(rule: any, value: string, callback: Function) {
  if (value === '' || typeof value === 'undefined' || value == null) {
    callback(new Error('请输入正确的IP地址'));
  } else {
    const reg =
      /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
    if (!reg.test(value) && value !== '') {
      callback(new Error('请输入正确的IP地址'));
    } else {
      callback();
    }
  }
}

/**
 * 校验合法请求地址
 * @param rule
 * @param value
 * @param callback
 */
export function validateURL(rule: any, value: string, callback: Function) {
  if (value === '' || typeof value === 'undefined' || value == null) {
    callback(new Error('请输入请求地址'));
  } else {
    const reg =
      /^(https?|ftp):\/\/([a-zA-Z\d.-]+(:[a-zA-Z\d.&%$-]+)*@)*((25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d?)(\.(25[0-5]|2[0-4]\d|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
    if (!reg.test(value) && value !== '') {
      callback(new Error('请输入正确的请求地址'));
    } else {
      callback();
    }
  }
}

/**
 * 校验端口号
 * @param rule
 * @param value
 * @param callback
 */
export function validatePort(rule: any, value: string, callback: Function) {
  if (!value) {
    callback(new Error('请输入端口号'));
  }
  setTimeout(() => {
    if (value === '') {
      callback(new Error('请输入端口号'));
    } else {
      const re =
        /^(\d|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;
      const rsCheck = re.test(value);
      if (!rsCheck) {
        callback(new Error('请输入在[0-65535]之间的端口值'));
      } else {
        callback();
      }
    }
  }, 100);
  callback();
}

/**
 * 校验字符串是不是标准的json
 * @param str
 */
export function validateJSON(str: string): boolean {
  try {
    const parse = JSON.parse(str);
    return typeof parse === 'object' && parse;
  } catch (e) {
    return false;
  }
}
